package com.xzg.erp.system.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import com.xzg.erp.common.BusinessException;
import com.xzg.erp.common.Constants;
import com.xzg.erp.common.WebConfig;
import com.xzg.erp.system.entity.Attachment;
import com.xzg.erp.system.mapper.AttachmentMapper;
import com.xzg.erp.system.service.IAttachmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;

/**
 * <p>
 * 附件表 服务实现类
 * </p>
 *
 * @author qwc
 * @since 2025-02-13
 */
@Service
public class AttachmentServiceImpl extends ServiceImpl<AttachmentMapper, Attachment> implements IAttachmentService {

    @Autowired
    private WebConfig webConfig;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveFile(MultipartFile file, int id, String tableName) {
        Attachment attachment = new Attachment();
        attachment.setRelatedTable(tableName);
        attachment.setRelatedTablePrimaryKey(id);
        attachment.setName(file.getOriginalFilename());
        if (file.isEmpty()) {
            throw new BusinessException(HttpStatus.INTERNAL_SERVER_ERROR, Constants.FILE_NOT_EXIT);
        }
        String newName = newName(file);
        String position = Constants.PRODUCT_IMAGES + Constants.SLASH + newName;
        try {
            Path path = Paths.get(webConfig.getFilePath(),newName);
            Files.write(path, file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(HttpStatus.INTERNAL_SERVER_ERROR, Constants.FILE_NOT_EXIT);
        }
        attachment.setPosition(position);
        attachment.setCreatedAt(LocalDateTime.now());
        attachment.setCreatedBy(StpUtil.getLoginIdAsInt());
        attachment.setType(file.getContentType());
        this.save(attachment);
    }

    public String newName(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            throw new BusinessException(HttpStatus.INTERNAL_SERVER_ERROR,Constants.FILE_INVALID);
        }

        // 提取后缀并处理大小写
        String extension = "";
        int dotIndex = originalFilename.lastIndexOf(".");
        if (dotIndex > 0) {
            extension = originalFilename.substring(dotIndex + 1).toLowerCase();
        }

        // 生成新名称并拼接后缀
        String newName = IdUtil.simpleUUID();
        return extension.isEmpty() ? newName : newName + "." + extension;
    }
}
